package com.fosung.frame.modules.sys.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.fosung.frame.common.config.Global;
import com.fosung.frame.common.persistence.Page;
import com.fosung.frame.common.utils.StringUtils;
import com.fosung.frame.common.web.BaseController;
import com.fosung.frame.modules.sys.entity.Param;
import com.fosung.frame.modules.sys.service.ParamService;

/**
 * 系统参数Controller
 * 
 * @author fosung
 * @version 2017-02-16
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/param")
public class ParamController extends BaseController {

	@Autowired
	private ParamService paramService;

	@ModelAttribute
	public Param get(@RequestParam(required = false) String id) {
		if (StringUtils.isNotBlank(id)) {
			return paramService.get(id);
		} else {
			return new Param();
		}
	}

	@RequiresPermissions("sys:param:view")
	@RequestMapping(value = { "list", "" })
	public String list(Param param, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Param> page = paramService.findPage(new Page<Param>(request, response), param);
		model.addAttribute("page", page);
		return "modules/sys/paramList";
	}

	@RequiresPermissions("sys:param:view")
	@RequestMapping(value = "form")
	public String form(Param param, Model model) {
		model.addAttribute("param", param);
		return "modules/sys/paramForm";
	}

	@RequiresPermissions("sys:param:edit")
	@RequestMapping(value = "save") // @Valid
	public String save(Param param, Model model, RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()) {
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/param/?repage";
		}
		if (!beanValidator(model, param)) {
			return form(param, model);
		}
		paramService.save(param);
		addMessage(redirectAttributes, "保存系统参数'" + param.getParamName() + "'成功");
		return "redirect:" + adminPath + "/sys/param/?repage";
	}

	@RequiresPermissions("sys:param:edit")
	@RequestMapping(value = "delete")
	public String delete(Param param, RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()) {
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/param/?repage";
		}
		paramService.delete(param);
		addMessage(redirectAttributes, "删除系统参数'" + param.getParamName() + "'成功");
		return "redirect:" + adminPath + "/sys/param/?repage";
	}

}
